import asyncio

from fastapi import FastAPI
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise

# 配置 MySQL 数据库
TORTOISE_ORM = {
    "connections": {
        "default": {
            "engine": "tortoise.backends.mysql",  # 数据库引擎 Mysql or Mariadb
            "credentials": {
                "host": "127.0.0.1",  # 地址
                "port": "3306",  # 端口
                "user": "root",  # 用户名
                "password": "gx20020225",  # 密码
                "database": "blog",  # 数据库名称（需要提前创建数据库）
                "minsize": 1,  # 最少连接
                "maxsize": 5,  # 最大连接

            }
        }
    },
    "apps": {
        "models": {
            "models": ["models.models","aerich.models"],  # models数据模型迁移
            "default_connection": "default"
        }
    },
    "use_tz": False,
    "timezone": "Asia/Shanghai"
}


async def register_mysql(app: FastAPI):
    """
    注册 MySQL 数据库到 FastAPI 应用。

    :param app: FastAPI 实例
    """
    await Tortoise.init(config=TORTOISE_ORM)


async def init_db(app):
    # 初始化 Tortoise ORM
    await Tortoise.init(config=TORTOISE_ORM)
    # 创建表
    await Tortoise.generate_schemas()


if __name__ == '__main__':
    app = FastAPI()
    # asyncio.run(register_mysql(app))
    asyncio.run(init_db(app))
